package org.ciallo.simplemusicplayer.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.PlaylistSelectionAdapter;
import org.ciallo.simplemusicplayer.data.model.PlaylistInfo;
import org.ciallo.simplemusicplayer.util.Constants;
import org.ciallo.simplemusicplayer.viewmodel.PlaylistViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jukomu
 * @Description: 用于将歌曲添加到现有歌单的选择对话框
 * @Package: org.ciallo.simplemusicplayer.dialog
 * @Project: SimpleMusicPlayer
 * @name: AddToPlaylistDialogFragment
 * @Date: 2025/6/3-05:33
 * @Filename: AddToPlaylistDialogFragment
 */
public class AddToPlaylistDialogFragment extends DialogFragment {
    public static final String TAG = "AddToPlaylistDialog";
    private static final String ARG_SONG_ID = "arg_song_id";

    private long songIdToAdd;
    private RecyclerView recyclerViewPlaylists;
    private PlaylistSelectionAdapter adapter;
    private TextView tvEmptyPlaylists;
    private PlaylistViewModel playlistViewModel;

    public static AddToPlaylistDialogFragment newInstance(long songId) {
        AddToPlaylistDialogFragment fragment = new AddToPlaylistDialogFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_SONG_ID, songId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            songIdToAdd = getArguments().getLong(ARG_SONG_ID, Constants.INVALID_INDEX);
        }
        if (songIdToAdd == Constants.INVALID_INDEX) {
            Timber.e("AddToPlaylistDialogFragment started with invalid songId.");
            dismissAllowingStateLoss(); // 无效参数，直接关闭
            return;
        }
        playlistViewModel = new ViewModelProvider(requireActivity()).get(PlaylistViewModel.class);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_add_to_playlist, null);

        recyclerViewPlaylists = view.findViewById(R.id.recyclerView_playlist_selection);
        tvEmptyPlaylists = view.findViewById(R.id.textView_empty_playlists_for_selection);

        setupRecyclerView();
        observePlaylists();

        builder.setView(view)
                .setTitle("添加到歌单")
                .setNegativeButton(R.string.cancel, (dialog, which) -> dismiss());
        // 没有 PositiveButton，因为点击列表项即完成操作

        return builder.create();
    }

    private void setupRecyclerView() {
        adapter = new PlaylistSelectionAdapter(playlistInfo -> {
            if (playlistInfo.id == Constants.FAVORITES_PLAYLIST_ID) {
                // "我的收藏" 是通过 FavoritesViewModel 添加的，这里不处理
                Toast.makeText(getContext(), "请通过歌曲选项中的“收藏”操作", Toast.LENGTH_SHORT).show();
                return;
            }
            // 添加到选中的普通歌单
            playlistViewModel.addSongToPlaylist(playlistInfo.id, songIdToAdd);
            Toast.makeText(getContext(), "已添加到歌单: " + playlistInfo.name, Toast.LENGTH_SHORT).show();
            dismiss(); // 操作完成后关闭对话框
        });
        recyclerViewPlaylists.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewPlaylists.setAdapter(adapter);
    }

    private void observePlaylists() {
        playlistViewModel.userPlaylistsToDisplay.observe(this, playlistInfos -> {
            if (playlistInfos != null) {
                // 从 allPlaylistsWithInfo 中过滤掉“我的收藏”这个特殊歌单项
                // 因为 addToPlaylist 通常是针对用户创建的普通歌单
                List<PlaylistInfo> userCreatedPlaylists = playlistInfos.stream()
                        .filter(pInfo -> pInfo.playlistType == PlaylistInfo.TYPE_NORMAL_PLAYLIST) // 仅普通歌单
                        .collect(Collectors.toList());

                if (!userCreatedPlaylists.isEmpty()) {
                    adapter.submitList(new ArrayList<>(userCreatedPlaylists)); // 提交副本
                    tvEmptyPlaylists.setVisibility(View.GONE);
                    recyclerViewPlaylists.setVisibility(View.VISIBLE);
                } else {
                    adapter.submitList(new ArrayList<>());
                    tvEmptyPlaylists.setText("还没有用户创建的歌单"); // 可以修改提示
                    tvEmptyPlaylists.setVisibility(View.VISIBLE);
                    recyclerViewPlaylists.setVisibility(View.GONE);
                }
            } else {
                tvEmptyPlaylists.setText("无法加载歌单列表");
                tvEmptyPlaylists.setVisibility(View.VISIBLE);
                recyclerViewPlaylists.setVisibility(View.GONE);
            }
        });
    }
}
